var TMR_STATUS_CALLBACK = 'update_tmr_status'
var TMR_STATUS_UPDATE_URL = 'http://music.tmradio.net/api/status.js?var=data&callback=' + TMR_STATUS_CALLBACK + '&';
var TMR_STATUS_SCRIPT_ID = 'tmr_status_script_update';
var tmr_current_status = {'id': null};

function force_tmr_status_update() {TMR_FORCE_STATUS_UPDATE = true; call_tmr_status_update();}
function call_tmr_status_update() { cdt_update_js(TMR_STATUS_UPDATE_URL, TMR_STATUS_SCRIPT_ID); }

if (typeof(tmr_before_status_update) == 'undefined') tmr_before_status_update = function(data) {};
if (typeof(tmr_after_status_update) == 'undefined') tmr_after_status_update = function(data) {};
if (typeof(tmr_on_new_status) == 'undefined') tmr_on_new_status = function(data) {};

function new_track(old_data, new_data) {
    if (!old_data) return true;
    return (old_data.id != new_data.id)
}
function track_is_changed(old_data, new_data) {
    if (!old_data) return true;
    return (
        old_data.id != new_data.id ||
        old_data.weight != new_data.weight || 
        old_data.labels.length != new_data.labels.length
    )
}

function update_tmr_status(data) {
    tmr_before_status_update(data); // callback 'before do'
    var track_changed = track_is_changed(tmr_current_status, data);
    // console.log("track_changed = " + track_changed);
    if (new_track(tmr_current_status, data)) {
        save_in_playlog(data);
        tmr_on_new_status(data); // callback on new status
    };

    if (track_changed || TMR_FORCE_STATUS_UPDATE) {
        tmr_current_status = data
        if (TMR_FORCE_STATUS_UPDATE) console.log('Forced TMR status update'); 
        document.getElementById('tmr_image').innerHTML = "";
        document.getElementById('tm_status_text').innerHTML = "";
        document.getElementById('tmr_download_link').innerHTML = "";

        // Artist and track names with search links
        var last_fm_link = 'http://www.lastfm.ru/music/' + data.artist.replace(/\s/g,'%20');
        var artist = document.createElement('a');
        // artist.href = last_fm_link;
        artist.href = '/search/?name=' + encodeURIComponent(data.artist);
        artist.innerHTML = data.artist;
        artist.title = "Искать исполнителя в базе данных ТМРадио";
        var track = document.createElement('a');
        //track.href = last_fm_link + '/_/' + data.title.replace(/\s/g,'%20');
        track.href = '/search/?name=' + data.id;
        track.title = "Показать композицию в базе данных ТМРадио";
        track.innerHTML = data.title;
        var status_text = track.outerHTML + ' by ' + artist.outerHTML;
        document.getElementById('tm_status_text').innerHTML = status_text;

        // Album image
        image = document.createElement('img');
        image.src = data.image || TMR_DEFAULT_IMAGE;
        document.getElementById('tmr_image').innerHTML = image.outerHTML;

        // Download links
        if (data.download) {
            var link = document.createElement('a');
            link.href = data.download; link.innerHTML = 'Скачать с LastFm';
            document.getElementById('tmr_download_link').innerHTML = link.outerHTML;
        } else { get_jamendo_link(data.artist, data.title); };
        
        // Track extended info - weight, length, number of playbacks and tags.
        track_info_string = get_track_info_string(data) + "<br>Теги: " + get_track_tags_string(data);
        document.getElementById('tmr_track_info').innerHTML = track_info_string;
    };

    // Планируем следующее обновление
    if (track_changed || TMR_FORCE_STATUS_UPDATE) {
        timer = seconds_before_end_of_track(data);
        console.log('Status will be updated after ' + timer + ' seconds');
        TMR_UPDATE_TIMER = window.setTimeout(call_tmr_status_update, (timer + 3) * 1000);
    };

    TMR_FORCE_STATUS_UPDATE = false;
    tmr_after_status_update(data);
};

function get_track_info_string(data) {
    var track_info = "Рейтинг песни %{weight}, длина %{length}, проигрываний %{count}";
    var length = Math.floor(data.length/60)+':'; if ( (data.length%60)<10 ) length += '0'; length += Math.round(data.length%60);
    track_info = track_info.replace("%{weight}", data.weight.toPrecision(3) );
    track_info = track_info.replace("%{length}", length);
    track_info = track_info.replace("%{count}", data.count);
    return track_info;
};

function get_track_tags_string(data) {
    var tags = "";
    for (i=0; i<data.labels.length; i+=1) {
        label = data.labels[i]; if (label == 'tagme') label = "<b>tagme</b>";
        if (tags.length > 0) label = ", "+label;
        if (label.indexOf(':') < 0) tags += label;
    };
    return tags;
};

function seconds_before_end_of_track(data) {
    seconds = data.length - (data.current_ts - data.last_played);
    console.log(seconds + ' seconds until the end of track');
    return seconds;
};

function set_jam_link(data) {
    if (data[0] != undefined) {
        var link = document.createElement('a');
        link.href = data[0]; link.innerHTML = 'Скачать весь альбом с Jamendo';
        document.getElementById('tmr_download_link').innerHTML = link.outerHTML;
    };
};

function get_jamendo_link(artist, title) {
    var url = "http://api.jamendo.com/ru/?artist_name="+escape(artist)+"&jsoncallbackfunction=set_jam_link&m=get2&m_params=url%2Falbum%2Fjson%2F&track_name="+escape(title);
    cdt_update_js(url, 'getjamendolink');
};

function get_recent_tracks() {
    var url = "http://music.tmradio.net/track/recent.js?callback=set_recent_tracks";
    // cdt_load_js(url);
    console.log(url);
    script = document.createElement('script');
    script.src = url;
    document.head.appendChild(script);
};

function set_recent_tracks(data) {
    if (data.status != 'ok') {
        console.log('Не получилось запросить список треков с music.tmradio.net');
        return
    };
    var tracks = data.tracks;
    console.log('got ' + tracks.length + ' recent tracks');
    for(var i = tracks.length - 1; i >= 0; i = i - 1) {
        save_in_playlog(tracks[i]);
    };
};

function save_in_playlog(data) {
    function generate_playlist_item(data) {
        var item = document.createElement('p');
        var title = data.title + ' - ' + data.artist;
        var info = get_track_info_string(data);
        // var tags = get_track_tags_string(data);
        var date = new Date(data.last_played * 1000);
        time = date.toLocaleTimeString().match(/([\d]+\:[\d]+)\:\d+/)[1];
        var votes = "<a href=# onclick='send_vote(\"rocks\", " + data.id + ", true); return false;' title='Rocks'>+</a>";
        votes += "/<a href=# onclick='send_vote(\"sucks\", " + data.id + ", true); return false;' title='Sucks'>-</a>";
        var track_info_string = time + " #" + data.id + " (" + votes + ") " + title;
        track_info_string += ".&nbsp;<font size=1>" + info + "</font>";
        item.innerHTML = track_info_string;

        item.id = 'track_' + data.id;
        return item;
    };
    function insert_item(item) {
        var playlog_el = document.getElementById('tmr_playlog');
        if (playlog_el) {
            playlog_el.insertBefore(item , playlog_el.firstChild );
            if (playlog_el.children.length > 20) {
                playlog_el.removeChild(playlog_el.lastChild);
            };
        };
    };
    if (!data) return;
    insert_item( generate_playlist_item(data) );
};
// Callback like onLoad, runs when script is loaded.
get_recent_tracks();

if (typeof(status_info_core_loaded) == 'undefined') { status_info_core_loaded = function() {}; };
status_info_core_loaded();